<template>
    <view class="order-list-container">
        <!-- https://z-paging.zxlee.cn/start/use.html#%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8 -->
        <z-paging 
            ref="paging" 
            v-model="orderList" 
            @query="handlerPullRefreshAndMore"
            @scroll="handleScroll"
            :default-page-size="params.page_size"
            class="order-list"
            :scroll-with-animation="true"
        >
            <!-- 状态栏区域 -->
            <template #top>
                <TridentFreshSearch @search="handlerSearchOrder" placeholder="搜索订单"/>
                
                <view class="tab-wrap">
                    <text class="tab-item" v-for="(item, index) in orderTabs" :key="index" @click="selectOrderTab(item.status)">{{ item.title }}</text>
                    <view class="cursor" :style="{ left: currentTab * 20 + '%' }"></view>
                </view>
            </template>

            <!-- 骨架屏区域 -->
            <view v-if="isShowSkeleton" style="background-color: #fff;margin: 20rpx;border-radius: 10rpx;" v-for="(item, index) in 3" :key="index">
                <uv-skeletons :loading="isShowSkeleton" :skeleton="skeleton"></uv-skeletons>
            </view>
            
            <!-- 订单区域 -->
            <view class="order-wrap" v-for="(order, index) in orderList" :key="index">
                <navigator
                    :url="`/pagesOrder/order_detail/index?oid=${order.oid}`"
                    hover-class="none"
                >
                    <!-- 订单头部区域 -->
                    <view class="title">
                        <view class="title-left">{{ order.create_time }}</view>

                        <view class="title-right">
                            <block v-for="(orderStatusItem, index) in orderStatusItems" :key="index">
                                <view class="tag-view">
                                    <uni-tag v-if="order.status == orderStatusItem.value" :mark="true" :text="orderStatusItem.value_txt" :custom-style="orderStatusItem.style" size="default" />
                                </view>
                            </block>
                        </view>
                    </view>

                    <!-- 订单明细区域 -->
                    <view class="order-item" v-for="(orderItem, index) in order.orderItems" :key="index">

                        <!-- 商品图片 -->
                        <view class="item-left">
                            <!-- #ifdef MP-WEIXIN -->
                            <image class="cover" :lazy-load="true" :src="global.FILE_DOMAIN + orderItem.goods_cover_url" />
                            <!-- #endif -->

                            <!-- #ifdef H5 -->
                            <img class="cover" v-img-lazy="global.FILE_DOMAIN + orderItem.goods_cover_url" />
                            <!-- #endif -->
                        </view>

                        <!-- 商品信息 -->
                        <view class="item-right">
                            <view class="goods-name ellipsis-2">{{ orderItem.goods_name }}</view>
                            <view class="goods-sku">{{ orderItem.goods_sku_text }}</view>
                        </view>
                    </view>

                    <!-- 订单价格区域 -->
                    <view class="price-box">
                        <text class="quantity">共{{ order.amount }}件商品</text>
                        <text>实付</text>
                        <view class="amount">
                            <text class="symbol">¥</text>
                            <text class="price">{{ (order.pay_money/100).toFixed(2) }}</text>
                        </view>
                    </view>
                </navigator>

                <!-- 订单操作按钮 -->
                <view class="action-wrap">
                    <!-- 待付款状态：显示去支付按钮 -->
                    <template v-if="order.status == 0">
                        <view @click="showCancelOrder(order.oid)" class="action-button cancel">取消订单</view>
                        <view @click="onOrderPay(order.oid)" class="action-button primary">去支付</view>
                    </template>
                    <template v-else>
                        <navigator
                            class="action-button secondary"
                            :url="`/pagesGoods/goods_detail/index?id=${order.orderItems[0].goods_id}`"
                            hover-class="none"
                        >
                            再次购买
                        </navigator>

                        <!-- 退款 -->
                        <view class="action-button primary" v-if="[1,2,3,4,5,6].includes(order.status)" @click="handleRefund(order.oid)">退 款</view>

                        <!-- 待收货状态: 展示确认收货 -->
                        <view v-if="[3,4,5].includes(order.status)" class="action-button primary" @click="handleConfirmOrder(order.oid)">确认收货</view>

                        <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
                        <view v-if="[-1,6,7].includes(order.status)" class="action-button primary" @click="handleDeleteOrder(order.oid)">删除订单</view>
                    </template>
                </view>
            </view>

            <!-- 加载更多提示 -->
            <template #loadingMoreNoMore>
                <view :style=" safeAreaInsets.bottom > 0 ? 'padding-bottom: ' + safeAreaInsets.bottom + 'px': ''" class="no-more" v-if="pageTotal == params.page && pageTotal > 1">我也是有底线的！</view>
            </template>

        </z-paging>

        <!-- 返回顶部 -->
		<TridentFreshBackTop @backTop="backTop" :isShowBackTop="isShowBackTop"/>

        <!-- 取消订单弹窗 -->
        <uni-popup ref="popup" type="bottom" background-color="#fff">
            <view class="popup-wrap">
                <view class="title">订单取消</view>
                <view class="description">
                    <view class="tips">请选择取消订单的原因：</view>
                    <view
                        class="cell"
                        v-for="item in reasonList"
                        :key="item"
                        @click="reason = item"
                    >
                        <text class="txt" :class="item === reason ? ' txt-checked' : ''">{{ item }}</text>
                        <text class="icon iconfont" :class="item === reason ? ' icon-checked icon-xuanzhong' : 'icon-weixuanzhong'"></text>
                    </view>
                </view>
                <view class="footer">
                    <view class="btn" @click="popup?.close?.()">取消</view>
                    <view @click="confirmCancelOrder()" class="btn primary">确认</view>
                </view>
            </view>
        </uni-popup>

    </view>
</template>

<script setup lang="ts">
import { reqCancelOrderAPI, reqConfirmOrderAPI, reqOrderListAPI, reqDeleteOrderAPI, reqPaymentOrderAPI, reqRefundOrderAPI } from '@/apis/order'
import { onShow } from '@dcloudio/uni-app'
import { reactive, ref, inject } from 'vue'
import { reqMpWxPayAPI } from '@/apis/payment'


// ----------------- 定义全局变量开始 -----------------
const paging = ref()

// 全局属性
const global:any = inject('global')

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// tabs 数据
const orderTabs = ref([
  { status: 0, title: '全部' },
  { status: 1, title: '待付款' },
  { status: 2, title: '待发货' },
  { status: 3, title: '待收货' },
  { status: 4, title: '待评价' },
])

// 当前订单tab
const currentTab = ref(0)

// 获取页面参数
const query:any = defineProps({
    "status": {
        type: String,
        default: '0'
    }
})

onShow(() => {
    currentTab.value = query.status * 1
})
// ----------------- 定义全局变量开始 -----------------



// ----------------- 定义骨架变量开始 -----------------
// 定义是否显示骨架
const isShowSkeleton = ref(false)

// 定义骨架参数
const skeleton = reactive([
    {
        type: 'flex',
        num: 1,
        style: 'margin-top: 20rpx;padding:0 20rpx;justify-content: space-between;align-items: center;',
        children: [
            {
                type: 'custom',
                num: 1,
                style: 'width: 350rpx;height: 40rpx'
            },
            {
                type: 'custom',
                num: 1,
                style: 'width: 120rpx;height: 50rpx;border-top-right-radius: 25rpx;border-bottom-right-radius: 25rpx;'
            },
        ]
    },
    20,
    {
        type: 'flex',
        num: 1,
        style: 'padding:0 20rpx',
        children: [
            {
                type: 'custom',
                num: 1,
                style: 'width: 160rpx;height:160rpx;marginLeft: 10rpx;marginRight: 20rpx;'
            },
            {
                type: 'line',
                num: 4,
                gap: '30rpx',
                style: [null, null, 'width:400rpx;', 'width:400rpx;']
            },
        ]
    },
    30,
    // 价格区域
    {
        type: 'flex',
        num: 1,
        style: 'margin-top: 20rpx;padding:0 20rpx;justify-content: flex-end;align-items: center;',
        children: [
            {
                type: 'custom',
                num: 1,
                style: 'width: 120rpx;height: 30rpx;margin-right:20rpx'
            },
            {
                type: 'custom',
                num: 1,
                style: 'width: 200rpx;height: 40rpx'
            },
        ]
    },
    30,
    {
        type: 'line',
        num: 1,
        style: 'height: 2rpx'
    },
    // 操作按钮区域
    {
        type: 'flex',
        num: 1,
        style: 'margin-top: 20rpx;padding:0 20rpx;justify-content: flex-end;align-items: center;',
        children: [
            {
                type: 'custom',
                num: 1,
                style: 'width: 200rpx;height: 60rpx;border-radius: 30rpx;margin-right: 20rpx;'
            },
            {
                type: 'custom',
                num: 1,
                style: 'width: 200rpx;height: 60rpx;border-radius: 30rpx;'
            },
        ]
    },
    20
])
// ----------------- 定义骨架变量结束 -----------------



// ----------------- 返回顶部功能开始 -----------------

// 定义是否显示返回顶部
const isShowBackTop = ref(false)

// 返回顶部
const backTop = () => {
    paging.value.scrollToTop()
}

// 当滚动触发时，调用事件用于显示、隐藏返回顶部图标
const handleScroll = (e:any) => {
    isShowBackTop.value = e.detail.scrollTop > 300 ? true : false
}
// ----------------- 返回顶部功能结束 -----------------



// ----------------- 搜索订单功能开始 -----------------
const handlerSearchOrder = (e:any) => {
    console.log(e);
    params.goods_name = e.keyword.value
    params.page = 1
    orderList.value = []

    paging.value.reload()
}
// ----------------- 搜索订单功能结束 -----------------



// --------------- 选择订单状态功能开始 ---------------
const selectOrderTab = (index:any) => {
    currentTab.value = index
    orderList.value = []
    // 当tab切换或搜索时，可以通过paging.value.reload()刷新整个列表
    paging.value.reload()
}
// --------------- 选择订单状态功能结束 ---------------



// --------------- 获取订单列表功能开始 ---------------
// 订单状态
const orderStatusItems:any = ref([])

// 订单列表
const orderList:any = ref([])

// 总数
const total = ref(0)

// 总页数
const pageTotal = ref(0)

// 订单列表请求参数
const params = reactive({
    status: "all",
    goods_name: '',
    is_delete: '0',
    page: 1,
    page_size: 10
})

// 获取订单列表
const getOrderList = async () => {
    // 显示骨架
    if (params.page == 1) {
        isShowSkeleton.value = true
    }

    params.status = currentTab.value == 0 ? "all": currentTab.value + ''
    const result:any = await reqOrderListAPI(params)
    let orders = result.data.orders != null ? result.data.orders : []
    total.value = result.data.total
    pageTotal.value = result.data.page_total

    // 组装订单状态数据
    if (orderStatusItems.value.length == 0) {
        result.data.status_items.forEach((item:any) => {
            let color = ''
            if (item.value == 0) { // 待付款
                color = '#E43D33'
            } else if (item.value == 1) { // 已付款
                color = '#18BC37'
            } else if (item.value == 2) { // 待发货
                color = '#F3A73F'
            } else if ([3,4,5].includes(item.value)) { // 已发货,已揽件,派件中
                color = '#2979FF'
            } else if (item.value == 6) { // 待评价
                color = '#E029F0'
            } else if (item.value == 7) { // 已完成
                color = '#03D8CE'
            } else if (item.value == 8) { // 退款中
                color = '#F76C6C'
            } else { // 已取消,已退款,已关闭...
                color = '#8F939C'
            }
            item.style = 'background-color: '+color+'; border-color: '+color+';color: #fff;'

            orderStatusItems.value.push(item as never)
        });
    }

    paging.value.complete(orders);

    // 隐藏骨架
    isShowSkeleton.value = false
}
// --------------- 获取订单列表功能结束 ---------------



// ------------- 下拉刷新 + 加载更多开始 --------------
const handlerPullRefreshAndMore = (pageNo:any, pageSize:any) => {
    params.page = pageNo
    getOrderList()
}
// -------------下拉刷新 + 加载更多结束 --------------



// ---------------- 取消订单功能开始 ----------------
// 弹出层组件
const popup = ref()
// 取消原因列表
const reasonList = ref([
  '商品无货',
  '不想要了',
  '商品信息填错了',
  '地址信息填写错误',
  '商品降价',
  '其它',
])
// 订单取消原因
const reason = ref('')

const orderId = ref(0)

// 显示取消订单弹层
const showCancelOrder = (oid:any) => {
  orderId.value = oid
  popup.value.open('bottom')
}

// 确定取消订单
const confirmCancelOrder = async () => {
    // 判断取消原因
    if (reason.value == '') {
        uni.showToast({
            icon: 'none',
            title: '请选择取消原因!',
            duration: 1000
        })

        return false
    }

    // 请求
    await reqCancelOrderAPI({oid: orderId.value, cancel_reason: reason.value})
    uni.showToast({
        title: '取消订单成功',
        duration: 1000
    })

    // 当currentTab是待付款栏时，需要将该订单从列表中删除
    if (currentTab.value == 1) {
        const index = orderList.value.findIndex((item:any) => item.oid == orderId.value)
        orderList.value.splice(index, 1)
    } else {
        const order = orderList.value.find((item:any) => item.oid == orderId.value)
        order.status = -1
    }

    popup.value?.close()
}
// ---------------- 取消订单功能结束 ----------------



// ---------------- 确认收货功能开始 ----------------
const handleConfirmOrder = (oid:any) => {
  uni.showModal({
	    content: '确定要确认收货吗?',
	    success: async (res) => {
	        if (res.confirm) {
                await reqConfirmOrderAPI(oid)
                uni.showToast({
                    title: '确认收货成功',
                    duration: 1000
                })

                if (currentTab.value == 3) {
                    const index = orderList.value.findIndex((item:any) => item.oid == oid)
                    orderList.value.splice(index, 1)
                } else {    
                    const order = orderList.value.find((item:any) => item.oid == oid)
                    order.status = 6
                }
	        }
	    }
	})
}
// ---------------- 确认收货功能结束 ----------------



// ------------------ 退款功能开始 ------------------
const handleRefund = (oid:any) => {
    uni.showModal({
	    content: '确定要退款吗?',
	    success: async (res) => {
	        if (res.confirm) {
                await reqRefundOrderAPI(oid)
                uni.showToast({
                    title: '退款成功',
                    duration: 1000
                })

                const index = orderList.value.findIndex((item:any) => item.oid == oid)
                orderList.value.splice(index, 1)
	        }
	    }
	})
}
// ------------------ 退款功能结束 ------------------



// ---------------- 删除订单功能开始 ----------------
const handleDeleteOrder = async (oid:any) => {
  uni.showModal({
    content:'删除的订单可以在电脑端查看!',
    success: async (res) => {
      if (res.confirm) {
        await reqDeleteOrderAPI(oid)
        uni.showToast({
          title: '删除成功',
          duration: 1000
        })

        const index = orderList.value.findIndex((item:any) => item.oid == oid)
        orderList.value.splice(index, 1)
      }
    }
  })
}
// ---------------- 删除订单功能结束 ----------------



// ---------------- 订单支付功能开始 ----------------
const onOrderPay = async (oid:any) => {
  // import.meta.env.DEV
  // #ifdef MP-WEIXIN
  // 后台获取微信支付的请求参数
  // const result = await reqMpWxPayAPI(oid)
  // wx.requestPayment(result.data)
  // #endif

  uni.showModal({
        content: '当前支付功能仅模拟模式?',
        success: async (res) => {
            if (res.confirm) {
                await reqPaymentOrderAPI(oid)
                uni.showToast({
                    title: '支付成功',
                    duration: 1000
                })

                const order = orderList.value.find((item:any) => item.oid == oid)
                order.status = 6

                setTimeout(() => {
                    uni.redirectTo({url: '/pagesOrder/payment_result/success?oid='+oid})
                }, 1000)
            }
        }
    })
}
// ---------------- 订单支付功能结束 ----------------
</script>

<style lang="scss">
.order-list-container {
    /*状态栏区域*/
    .tab-wrap {
        height: 100rpx;
        line-height: 100rpx;
        background-color: #fff;

        display: flex;
        justify-content: center;
        position: relative;
        .tab-item {
            flex: 1;
            text-align: center;
        }
        .cursor {
            position: absolute;
            left: 0;
            bottom: 1rpx;

            width: 20%;
            height: 6rpx;
            background-color: #008000;
            transition: all 0.3s linear;
        }
    }
    /*订单列表区域*/
    .order-list {
        .order-wrap {
            background-color: #fff;
            padding: 20rpx;
            margin: 20rpx;
            border-radius: 10rpx;

            /*订单头部区域*/
            .title {
                display: flex;
                justify-content: space-between;
                margin-bottom: 20rpx;
            }

            /*订单明细区域*/
            .order-item {
                display: flex;
                padding: 10rpx;
                border-top: 2rpx dashed #ccc;

                .item-left {
                    width: 140rpx;
                    height: 140rpx;
                    .cover {
                        width: 100%;
                        height: 100%;
                    }
                }
                .item-right {
                    flex: 1;
                    padding: 0 15rpx;
                    .goods-name {
                        font-size: 28rpx;
                    }
                    .goods-sku {
                        background-color: #F7F7F8;
                        font-size: 24rpx;
                        color: #929292;
                        margin: 10rpx 0;
                        padding: 10rpx;
                    }
                }
            }

            /*订单价格*/
            .price-box {
                display: flex;
                justify-content: flex-end;
                align-items: center;
                padding: 20rpx 0;
                border-bottom: 2rpx solid #ccc;
                .quantity {
                    font-size: 26rpx;
                    margin-right: 20rpx;
                }
                .amount {
                    .symbol {
                        color: #CD0011;
                        font-size: 24rpx;
                        margin-left: 6rpx;
                    }
                    .price {
                        color: #CD0011;
                        font-size: 34rpx;
                    }
                }
            }

            /*操作区域*/
            .action-wrap {
                display: flex;
                justify-content: flex-end;
                padding-top: 20rpx;
                .action-button {
                    height: 60rpx;
                    line-height: 60rpx;
                    width: 200rpx;
                    text-align: center;
                    background-color: #fff;
                    border: 2rpx solid #CD0011;
                    color: #CD0011;
                    margin-left: 20rpx;
                    border-radius: 30rpx;
                    font-size: 28rpx;
                }
                .primary {
                    background-color: #CD0011;
                    color: #fff;
                }
                .cancel {
                    border: 2rpx solid gray;
                    color: gray;
                }
            }
        }

        // 没有更多区域
        .no-more {
            text-align: center;
            padding-bottom: 20rpx;
            color: #ccc;
            &::before {
                content: '-------------';
                margin-right: 10rpx;
            }
            &::after {
                content: '-------------';
                margin-right: 10rpx;
            }
        }
    }
}

// 取消订单弹窗开始
.popup-wrap {
    .title {
        font-size: 34rpx;
        text-align: center;
        padding: 20rpx 0;
        border-bottom: 2rpx solid #ccc;
    }
    .description {
        padding: 0 20rpx;
        .tips {
            font-size: 32rpx;
            padding-top: 20rpx;
        }
        .cell {
            display: flex;
            justify-content: space-between;
            padding: 14rpx 0;

            color: gray;
            .txt {
                font-size: 28rpx;
            }
            .txt-checked {
                color: #CD0011;
            }
            .icon {
                font-size: 36rpx;
            }
            .icon-checked {
                color: #CD0011;
            }
        }
    }
    .footer {
        display: flex;
        padding: 20rpx;
        justify-content: space-evenly;
        .btn {
            padding: 16rpx 100rpx;
            border: 2rpx solid #CD0011;
            border-radius: 40rpx;
            color: #CD0011;
        }
        .primary {
            color: #fff;
            background-color: #CD0011;
        }
    }
}
// 取消订单弹窗结束
</style>